import { IVec2, Rect, Size, UITransform } from "cc";
import { DynamicScrollView } from "../DynamicScrollView";
import { Item } from "../Item";

export abstract class DynamicScrollViewLayoutBase {
    /**画布的尺寸 */
    protected get size(): Size {
        return this.view.scrollView.view!.contentSize;
    }
    /**预制体锚点 需要和预制体本身的锚点设置一致 */
    private _anchor: IVec2 = { x: 0.5, y: 0.5 };
    public get anchor(): IVec2 {
        return this._anchor;
    }
    protected set anchor(value: IVec2) {
        this._anchor = value;
    }
    /**结点数据列表 */
    private _ItemBases: Item[] = [];
    protected get ItemBases(): Item[] {
        return this._ItemBases;
    }
    private set ItemBases(value: Item[]) {
        this._ItemBases = value;
    }

    protected view!: DynamicScrollView;

    Get_Item_By_Index(index: number): Item | null {
        for (let i = 0; i < this.ItemBases.length; i++) {
            if (this.ItemBases[i].index === index) {
                return this.ItemBases[i];
            }
        }
        return null;
    }

    init(view: DynamicScrollView) {
        this.view = view;

        this.beforeInitContentSize();
        this.initContentSize();
        this.afterInitContentSize();
    }

    protected beforeInitContentSize(): void {
        //初始化钩子函数
    }

    protected afterInitContentSize(): void {
        //初始化钩子函数
    }

    /**获取可见的item列表 */
    public abstract getDisplayItemList(): Item[];

    public getAllItem(): Item[] {
        return this.ItemBases;
    }

    public pushBackWithCount(count: number) {
        for (let i = 0; i < count; i++) {
            this.ItemBases.push(new Item(this.ItemBases.length, this.buildBackItemRect(this.ItemBases.length)));
        }
        this.initContentSize();
        //通知需要更新列表
        this.view.needUpdate();
    }

    //刷新全部结点
    public refreshAll() {
        const size = this.ItemBases.length;
        this.view.destroyAllChildren();
        this.ItemBases.length = 0;
        this.pushBackWithCount(size);
    }

    protected abstract buildBackItemRect(index: number): Rect;

    /**
     * 清空列表
     */
    public clean() {
        //通知需要更新列表
        this.view.destroyAllChildren();
        this.ItemBases.length = 0;
        this.initContentSize();
    }

    private initContentSize() {
        this.view.scrollView.content!.getComponent(UITransform)!.contentSize = this.getContentSize();
    }

    protected abstract getContentSize(): Size;

    /**尺寸变更消息 */
    sizeChangedEvent() {
        this.refreshAll();
    }
}